var express = require("express");
var router = express.Router();
var {
  petroleumModel,
  titleModel,
  commentModel,
  pathModel,
  userModel,
  citysModel,
} = require("../module/mbw_db");
let jwt = require("jsonwebtoken");
let mp = require("multiparty");
/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

router.post("/upload", async (req, res) => {
  let form = new mp.Form();
  form.uploadDir = "upload";
  form.parse(req, (err, data, img) => {
    console.log(img.file[0]);
    res.send({
      img: "http://localhost:3050/" + img.file[0].path,
    });
  });
});

router.get("/city", async (req, res) => {
  let data = await citysModel.find();
  res.send({
    code: 200,
    data,
  });
});

router.post("/login", async (req, res) => {
  let body = req.body;
  let data = [];
  let obj = {};
  let cates = await userModel
    .find({ username: body.username, pwd: body.pwd })
    .populate("pid")
    .lean();
  cates[0].pid.forEach((item) => {
    obj[item._id] = item;
  });
  cates[0].pid.forEach((item) => {
    if (!item["cid"]) {
      data.push(item);
    } else {
      if (!obj[item["cid"]]["children"]) {
        obj[item["cid"]]["children"] = [];
      }
      obj[item["cid"]]["children"].push(item);
    }
  });
  cates[0].pid = data;
  if (data[0]) {
    let token = "Bearer" + " " + jwt.sign(body, "flag", { expiresIn: "1d" });
    res.send({
      cates,
      token,
      msg: "登录成功",
      code: 200,
    });
  } else {
    res.send({
      msg: "登录失败",
    });
  }
});

router.get("/user_ls", async (req, res) => {
  let { pagenum, pagesize, title, impression, position } = req.query;
  let data = [];
  let obj = {};
  let cates;
  if (title) {
    title = new RegExp(title, "i");
    cates = await userModel
      .find({
        username: title,
      })
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize)
      .populate("pid")
      .lean();
  } else {
    cates = await userModel
      .find()
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize)
      .populate("pid")
      .lean();

    cates[0].pid.forEach((item) => {
      obj[item._id] = item;
    });
    cates[0].pid.forEach((item) => {
      if (!item["cid"]) {
        data.push(item);
      } else {
        if (!obj[item["cid"]]["children"]) {
          obj[item["cid"]]["children"] = [];
        }
        obj[item["cid"]]["children"].push(item);
      }
    });
    cates[0].pid = data;
  }
  let total = (await userModel.find()).length;
  res.send({
    cates,
    total,
  });
});

router.post("/user_add", async (req, res) => {
  let body = req.body;
  await userModel.create(body);
  res.send({
    code: 200,
  });
});

router.post("/user_edit/:id", async (req, res) => {
  let id = req.params.id;
  let body = req.body;
  console.log(body);
  console.log(id);
  await userModel.updateMany({ _id: id }, { $set: body });
  res.send({ code: 200 });
});

router.post("/user_tree/:id", async (req, res) => {
  let id = req.params.id;
  let body = req.body;
  await userModel.updateMany({ _id: id }, { $set: body });
  res.send({ code: 200 });
});

router.post("/user_del/:id", async (req, res) => {
  let id = req.params.id;
  await userModel.deleteOne({ _id: id });
});

router.get("/menu", async (req, res) => {
  let cates = await pathModel.find().lean();
  let data = [];
  let obj = {};

  cates.forEach((item) => {
    obj[item._id] = item;
  });
  cates.forEach((item) => {
    if (!item["cid"]) {
      data.push(item);
    } else {
      // console.log(obj[item["children"]]);
      if (!obj[item["cid"]]["children"]) {
        obj[item["cid"]]["children"] = [];
      }
      obj[item["cid"]]["children"].push(item);
    }
  });
  res.send({
    data,
  });
});

router.get("/petroleum_list", async (req, res) => {
  let { pagenum, pagesize, title, impression, position } = req.query;
  console.log(title, impression, position);
  let data;

  if (title) {
    title = new RegExp(title, "i");
    data = await petroleumModel
      .find({
        title,
      })
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize);
  } else if (impression) {
    impression = new RegExp(impression);

    data = await petroleumModel
      .find({
        impression,
      })
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize);
  } else if (position) {
    position = new RegExp(position);

    data = await petroleumModel
      .find({
        position,
      })
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize);
  } else {
    data = await petroleumModel
      .find()
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize);
  }
  let total = (await petroleumModel.find()).length;

  res.send({
    code: 200,
    data,
    total,
  });
});

router.post("/petroleum_add", async (req, res) => {
  let body = req.body;
  await petroleumModel.create(body);
  res.send({
    code: 200,
  });
});

router.post("/petroleum_edit/:id", async (req, res) => {
  let id = req.params.id;
  let body = req.body;
  await petroleumModel.updateMany({ _id: id }, { $set: body });
  res.send({
    code: 200,
  });
});

router.post("/petroleum_del/:id", async (req, res) => {
  let id = req.params.id;
  await petroleumModel.deleteOne({ _id: id });
  res.send({
    code: 200,
  });
});

router.get("/title_list", async (req, res) => {
  let data = await titleModel.find().populate("cid");
  res.send({
    code: 200,
    data,
  });
});

router.get("/comment_list", async (req, res) => {
  let { pagenum, pagesize, title, tid } = req.query;
  let data;
  if (title) {
    title = new RegExp(title);
    data = await commentModel
      .find({
        title,
      })
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize);
  } else {
    data = await commentModel
      .find()
      .populate("tid")
      .limit(Number(pagesize))
      .skip((Number(pagenum) - 1) * pagesize);
  }
  let total = (await commentModel.find()).length;

  res.send({
    code: 200,
    data,
    total,
  });
});

router.post("/comment_add", async (req, res) => {
  let body = req.body;
  await commentModel.create(body);
  res.send({
    code: 200,
  });
});

router.post("/comment_edit/:id", async (req, res) => {
  let id = req.params.id;
  let body = req.body;
  await commentModel.updateMany({ _id: id }, { $set: body });
  res.send({
    code: 200,
  });
});

router.post("/comment_del/:id", async (req, res) => {
  let id = req.params.id;
  await commentModel.deleteOne({ _id: id });
  res.send({
    code: 200,
  });
});

module.exports = router;
